package com.boatAnchorAssistant.service.bean.security.impl;

import com.boatAnchorAssistant.service.bean.security.Blacklist;
import lombok.Data;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author Joseph.Li
 * @author joseph.li@king-v.com
 * Created in 2022-07-12 14:58
 *
 * redisn 黑名单
 */
@Component
public class RedisBlacklist implements Blacklist {

    private final static String keyHead="black_head_";

    private final StringRedisTemplate redisTemplate;

    public RedisBlacklist(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;



    }


    /**
     * 保存一条记录
     * @param content 内容
     * @param time 时间
     * @param unit 时间单位
     */
    @Override
    public void save(String content, Long time, TimeUnit unit) {
        String key = getKey(content);
        redisTemplate.opsForValue().set(key,content,time,unit);
    }

    /**
     * 检查黑名单
     * @param content 内容
     * @return
     */
    @Override
    public Boolean check(String content) {
        String key = getKey(content);
        String value = redisTemplate.opsForValue().get(key);
        return StringUtils.hasText(value);
    }

    /**
     * 返回key
     * @param content
     * @return
     */
    private String getKey(String content){
        return keyHead+"-"+content;
    }
}
